package com.ltsznh.android.heartrate;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraDevice;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.ltsznh.android.heartrate.db.dbo;
import com.ltsznh.android.heartrate.util.Tools;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MainActivity extends Activity implements Camera.PreviewCallback {
    private AdView adView;


    private Camera camera;
    private CameraDevice camera2;
    private LinearLayout llC;

    private CheckBox flashLamp;

    private SurfaceView svCamera;
    private SurfaceHolder shCamera;

    private Camera.PreviewCallback pcData;

    private boolean isTest = false;//是否正在测试
    private boolean isSaved = false;
    ;

    private int count;

    public static EditText etRate;
    public static EditText etRateCount;
    public static EditText etTime;
    private RateView svRate;

    public static NumberPicker npAdjust;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar actionBar = this.getActionBar();
        actionBar.setDisplayShowHomeEnabled(true);
//        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.show();

        //************广告开始************//
        // 创建adView。
        adView = new AdView(this);
        adView.setAdUnitId("ca-app-pub-6427167969550621/5778606191");
        adView.setAdSize(AdSize.SMART_BANNER);

//        320x50	标准横幅广告	手机和平板电脑	BANNER
//        320x100	大横幅	手机和平板电脑	LARGE_BANNER
//        300x250	IAB中矩形	手机和平板电脑	MEDIUM_RECTANGLE
//        468x60	IAB全尺寸横幅广告	平板电脑	FULL_BANNER
//        728x90	IAB页首横幅广告	平板电脑	LEADERBOARD
//        查看表格	智能横幅广告	手机和平板电脑	SMART_BANNER

        // 查询LinearLayout，假设其已指定
        // 属性android:id="@+id/mainLayout"。
        LinearLayout layout = (LinearLayout) findViewById(R.id.adMob);

        // 在其中添加adView。
        layout.addView(adView);

//        Bundle bundle = new Bundle();
//        bundle.putString("color_bg", "AAAAFF");//背景颜色
//        bundle.putString("color_bg_top", "FFFFFF");//顶部的渐变背景色
//        bundle.putString("color_border", "FFFFFF");//边框颜色
//        bundle.putString("color_link", "000080");//链接文字颜色
//        bundle.putString("color_text", "808080");//文字颜色
//        bundle.putString("color_url", "008000");//网址颜色

//        AdMobExtras extras = new AdMobExtras(bundle);

        // 启动一般性请求。
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)          // 模拟器
                .addTestDevice("A03EE007D61ACD6F477499B09E1CF201") // 我的Galaxy Nexus测试手机
//                .addNetworkExtras(extras)//设置主题
                .build();

        // 在adView中加载广告请求。
        adView.loadAd(adRequest);
        //************广告结束************//
        dbo.initDatabase(MainActivity.this);

        llC = (LinearLayout) findViewById(R.id.llCamera);
        flashLamp = (CheckBox) findViewById(R.id.cbFlashLamp);

        etRateCount = (EditText) findViewById(R.id.etRateCount);
        etRate = (EditText) findViewById(R.id.etRate);
        etTime = (EditText) findViewById(R.id.etTime);

        npAdjust = (NumberPicker) findViewById(R.id.npAdjust);

        npAdjust.setMinValue(0);
        npAdjust.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                float time = Float.parseFloat(etTime.getText().toString());
                if (time == 0) return;
//                int rateCount = newVal;
                etRateCount.setText("" + newVal);
                etRate.setText("" + (int) (60 / ((float) time / newVal)));
                isSaved = false;
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void llCClick(View v) {
        if (svCamera == null) svCamera = (SurfaceView) findViewById(R.id.svCamera);
        if (shCamera == null) {
            shCamera = svCamera.getHolder();
            shCamera.addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                }

                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                }

                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    if (isTest) {
                        if(camera != null){
                            camera.setPreviewCallback(null);
                            camera.stopPreview();
                            camera.release();
                            camera = null;
                        }
                    }
                }
            });
        }
        svRate = (RateView) findViewById(R.id.svRate);
        svRate.thread.reset();

        PackageManager pm = this.getPackageManager();
        FeatureInfo[] featureInfos = pm.getSystemAvailableFeatures();
        for (FeatureInfo f : featureInfos) {//判断是否有闪光灯
            if (PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) {
                if (null == camera) {//打开
//                    svRate.thread.start();
                    etRate.setText("0");
                    etRateCount.setText("0");
                    etTime.setText("0");
                    isTest = true;
                    isSaved = false;
                    count = 0;
                    camera = Camera.open();
                    Camera.Parameters parameters = camera.getParameters();
                    if (flashLamp.isChecked())
                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                    camera.setPreviewCallback(pcData);
                    Camera.Size size = camera.getParameters().getPreviewSize();
                    camera.setDisplayOrientation(90);

//                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(size.width,size.height);
//                    svCamera.setLayoutParams(lp);
                    try {
                        camera.setPreviewDisplay(shCamera);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    camera.setParameters(parameters);
                    camera.setPreviewCallback(this);

                    camera.startPreview();
                    camera.autoFocus(null);//自动对焦
                } else {//关闭
                    closeTest();
                }

            }
        }
    }

    private void closeTest() {
        //                    Paint paint = new Paint();
//                    paint.setColor(Color.BLUE);
//                    Canvas canvas = new Canvas();
//                    canvas.drawText("Test",10,10,paint);
//                    svCamera.draw(canvas);
        isTest = false;
//         svRate.thread.
        camera.setPreviewCallback(null);
        camera.stopPreview();
        camera.release();
        camera = null;

    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if (count++ < 20) return;
        int total = data.length;

        int yy = 0;
//        int uu = 0;
//        int vv = 0;

        int f = data.length / 10;
        for (int i = 0; i < f; i++) {
            yy = yy + data[i * 10];
        }
        if (svRate.thread.setValue(yy)) {
            closeTest();
        } else {
            svRate.thread.run();
        }
    }

    public void save(MenuItem menuItem) {
        if (isTest) {
            Toast.makeText(MainActivity.this, getResources().getText(R.string.save_is_test), Toast.LENGTH_SHORT).show();
            return;
        }

        if (Integer.parseInt(etRate.getText().toString()) > 0) {
            if (isSaved) {
                Toast.makeText(MainActivity.this, getResources().getText(R.string.save_save), Toast.LENGTH_SHORT).show();
                return;
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("HH:mm:ss");
            ContentValues values = new ContentValues();
            values.put("id", Tools.getId());
            values.put("hrTime", etTime.getText().toString());
            values.put("hrCount", etRateCount.getText().toString());
            values.put("hrRate", etRate.getText().toString());
            values.put("entryDate", simpleDateFormat.format(new Date()));
            values.put("entryTime", simpleTimeFormat.format(new Date()));

            long i = dbo.insertData(MainActivity.this, "heart_rate_details", null, values);
            if (i > 0) {
                isSaved = true;
                Toast.makeText(MainActivity.this, getResources().getText(R.string.save_success), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(MainActivity.this, getResources().getText(R.string.save_no_rate), Toast.LENGTH_SHORT).show();
        }

    }

    public void history(MenuItem menuItem) {
        Intent intent = new Intent();
        intent.setClass(this, HistoryActivity.class);
//        intent.putExtra("invDate","");
        startActivity(intent);
    }

}
